<template>
<div class="mod-menu">
  <el-row :gutter="20">
    <el-col :span="2" style="marginTop:10px;">
      <span>允许拖拽</span>
      <el-switch v-model="dragEnabled" active-color="#13ce66" inactive-color="#ff4949">
      </el-switch>
    </el-col>
    <el-col :span="2" style="marginTop:10px;">
      <span>显示多选框</span>
      <el-switch v-model="checkboxEnabled" active-color="#13ce66" inactive-color="#ff4949">
      </el-switch>
    </el-col>

    <el-col :span="2">
      <div>
        <el-button :disabled="!dragEnabled || updateNodes.length == 0" @click="sendUpdateSortRequest" disab>保存修改</el-button>
      </div>
    </el-col>

    <el-col :span="1">
      <el-button :disabled="!checkboxEnabled" @click="sendDeleteBatchRequest" disab>批量删除</el-button>
    </el-col>

  </el-row>

  <el-tree :data="dataList" :draggable="dragEnabled" node-key="catId" :props="defaultProps" auto-expand-parent :show-checkbox="checkboxEnabled" :expand-on-click-node="false" :default-expanded-keys="defaultExpandedKeys" :allow-drop="allowDrop" :allow-drag="allowDrag" @node-drop="handleDrop" ref="categoryTree">

    <span class="custom-tree-node" slot-scope="{ node, data }">
      <span>{{ node.label }}</span>
      <span>
        <el-button type="text" size="mini" v-if="node.level<=2" @click="handleAppend(data)">
          新增
        </el-button>
        <el-button type="text" size="mini" @click="handleUpdate(data)">
          编辑
        </el-button>
        <el-button type="text" size="mini" v-if="node.childNodes==0" @click="remove(node, data)">
          删除
        </el-button>
      </span>
    </span>

  </el-tree>

  <!-- 弹窗, 新增 / 修改 -->
  <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
    <el-form :model="dataForm">
      <el-form-item label="分类名称" :label-width="formLabelWidth">
        <el-input v-model="dataForm.name" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="doAddOrUpdate()">确 定</el-button>
    </div>
  </el-dialog>

</div>
</template>

<script>
export default {
  data() {
    return {
      dataForm: {
        name: ""
      },
      pCid: [],
      dataList: [],
      updateNodes: [],
      checkedNodeIds: [],
      dataListLoading: false,
      dialogFormVisible: false,
      dragEnabled: false,
      checkboxEnabled: false,
      defaultExpandedKeys: [],
      dialogTitle: "新增",
      formLabelWidth: '120px',
      maxLevel: 1,
      currentSort: null,
      defaultProps: {
        key: 'catId',
        children: 'subList',
        label: 'name'
      }
    }
  },
  async activated() {
    this.getDataList()
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({
        //解构函数
        data
      }) => {
        this.dataList = data.data
      })
    },

    // 删除
    remove(node, data) {
      let pid = data.parentCid;
      let params = [data.catId]
      this.$confirm(`确定删除分类[${data.name}]?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/product/category/delete`),
          method: 'post',
          data: this.$http.adornData(params, false)
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.getDataList()
            this.defaultExpandedKeys = [pid]

            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch((err) => {
        console.log("err:", err)
        console.log("用户取消了删除操作:", data.catId)
      })
    },

    //点击新增按钮的相应
    handleAppend(data) {
      this.dialogFormVisible = true
      this.dataForm.parentCid = data.catId
      this.dataForm.catLevel = data.catLevel * 1 + 1
      this.dataForm.name = ''
      this.dataForm.showStatus = 1
      this.dialogTitle = "新增"

      let obj = Object.assign(data.subList)
      let maxSortItem = obj.pop()
      this.dataForm.sort = maxSortItem.sort + 1
    },

    //点击编辑按钮的相应
    handleUpdate(data) {
      this.dialogFormVisible = true
      data.subList = []
      this.dataForm = Object.assign(data)
      this.dialogTitle = "编辑"
    },

    //点击确认按钮,执行添加操作
    doAddOrUpdate() {
      let isAdd = this.dataForm.catId == null
      this.$http({
        url: this.$http.adornUrl(isAdd ? `/product/category/save` : `/product/category/update`),
        method: 'post',
        data: this.$http.adornData(this.dataForm, false)
      }).then(({
        data
      }) => {
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 1500
        })
        this.dialogFormVisible = false
        this.getDataList()
        this.defaultExpandedKeys = [isAdd ? this.dataForm.parentCid : this.dataForm.catId]
      }).catch((err) => {
        console.log("数据提交异常,", err)
      })
    },

    //
    allowDrop(draggingNode, dropNode, type) {
      //1.计算被拖动的当前节点的总层数
      this.countNodeLevel(draggingNode);
      //当前节点的最大字节点level - 当前节点level + 1就是深度
      let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
      if (type == "inner") {
        return deep + dropNode.level <= 3;
      } else {
        return deep + dropNode.parent.level <= 3;
      }

    },

    allowDrag() {
      return true
    },

    //计算当前节点的最深层次的catLevel 不是实际层数
    countNodeLevel(node) {
      if (node.childNodes != null && node.childNodes.length > 0) {
        node.childNodes.forEach((item) => {
          if (item.level > this.maxLevel) {
            this.maxLevel = item.level;
          }
          this.countNodeLevel(item)
        })
      } else {
        this.maxLevel = node.level
      }
    },

    handleDrop(draggingNode, dropNode, type, event) {
      //type     before  after  inner
      let pCid = 0;
      let siblings = null
      let level = 1;
      console.log("dropNode:", dropNode)
      if ("inner" == type) {
        //父id 
        pCid = dropNode.data.catId
        siblings = dropNode.childNodes
        level = dropNode.data.catLevel + 1
        console.log("dropNode.data.level:", level)
        //顺序
      } else {
        pCid = dropNode.parent.data.catId == undefined ? 0 : dropNode.parent.data.catId
        siblings = dropNode.parent.childNodes
        level = dropNode.data.catLevel
        console.log("dropNode.data.level:", level)
      }

      for (let i = 0; i < siblings.length; i++) {
        let updateNode = {
          catId: siblings[i].data.catId,
          sort: (i + 1),
          catLevel: level,
          catName: siblings[i].data.catName
        }
        //父id
        if (siblings[i].data.catId == draggingNode.data.catId) {
          updateNode.parentCid = pCid;
        }
        this.updateNodes.push(updateNode)
      }
      this.pCid.push(pCid)
      console.log("当前需要展开的节点id:", this.defaultExpandedKeys)
      console.log("收集到的数据是:", JSON.stringify(this.updateNodes))
    },

    sendUpdateSortRequest() {
      //发送请求
      this.$http({
        url: this.$http.adornUrl(`/product/category/update/sort`),
        method: 'post',
        data: this.$http.adornData(this.updateNodes, false)
      }).then(({
        data
      }) => {
        this.$message({
          message: '操作成功',
          type: 'success',
          duration: 1500
        })
        this.updateNodes = []
        this.maxLevel = 0
        this.defaultExpandedKeys = this.pCid
      }).catch((err) => {
        console.log("数据提交异常,", err)
      })

    },

    sendDeleteBatchRequest() {
      let checkedNodes = this.$refs.categoryTree.getCheckedNodes();
      checkedNodes.forEach(item => {
        this.checkedNodeIds.push(item.catId)
      })
      this.$confirm(`确定删除选中的[${this.checkedNodeIds.length}]个分类?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/product/category/delete`),
          method: 'post',
          data: this.$http.adornData(this.checkedNodeIds, false)
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.getDataList()

            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
            })
          } else {
            this.$message.error(data.msg)
          }
        })
      }).catch((err) => {
        console.log("err:", err)
        console.log("用户取消了删除操作")
      })
    }

  }
}
</script>

<style>
.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
